import {
  AGConnectUser,
  PhoneAuthProvider,
  VerifyCodeAction,
  VerifyCodeSettingBuilder,
  EmailAuthProvider
} from '@hw-agconnect/auth-ohos';

import '@hw-agconnect/auth-ohos';
import { AGCApi } from '@hw-agconnect/api-ohos';
import { LogUtil } from '../common/utils/LogUtil';
import { getAGConnect } from './AgcConfig';
import { AgUser } from '../common/base/AgUser';

export class AGCAuth {
  agc: AGCApi;

  constructor(context) {
    this.agc = getAGConnect(context);
  }

  getCurrentUser = (): Promise<AGConnectUser> => {
    return this.agc.auth().getCurrentUser();
  }

  // 申请邮箱验证码
  requestEmailVerifyCode = (email: string) => {
    const verifyCodeSettings = new VerifyCodeSettingBuilder()
      .setAction(VerifyCodeAction.REGISTER_LOGIN)
      .setLang('zh_CN')
      .setSendInterval(60)
      .build();
    this.agc.auth().requestEmailVerifyCode(email, verifyCodeSettings)
      .then((ret) => {
        LogUtil.info(`Verify Code Result: ${JSON.stringify(ret)}`);
      }).catch((err) => {
      LogUtil.error(`Verify Code Failed. Cause: ${JSON.stringify(err)}`);
    })
  }

  // 申请手机号码验证码
  requestPhoneVerifyCode = (ctrCode: string, phone: string) => {
    const verifyCodeSettings = new VerifyCodeSettingBuilder()
      .setAction(1001)
      .setLang('zh_CN')
      .setSendInterval(60)
      .build();
    this.agc.auth().requestPhoneVerifyCode(
      ctrCode,
      phone,
      verifyCodeSettings
    ).then((ret) => {
      LogUtil.info(`Verify Code Result: ${JSON.stringify(ret)}`);
    }).catch((err) => {
      LogUtil.error(`Verify Code Failed. Cuase: ${JSON.stringify(err)}`);
    })
  }

  // 邮箱账号注册登录
  loginByEmail = async (email: string, verifyCode: string): Promise<AgUser> => {
    return new Promise((resolve, reject) => {
      // 如果创建账号的时候没有设置过密码，则只能通过此接口进行登录
      const credential = EmailAuthProvider.credentialWithVerifyCode(email, verifyCode);
      // 登录接口，通过第三方认证来登录AGConnect平台
      this.agc.auth().signIn(credential).then(async (ret) => {
        LogUtil.info(`User has signed in. User: ${JSON.stringify(ret)}`);
        const user: AGConnectUser = ret.getUser();
        const userExtra = await ret.getUser().getUserExtra();
        let loginRes: AgUser = {
          uid: user.getUid(),
          email: user.getEmail().toString(),
          photoUrl: user.getPhotoUrl().toString(),
          displayName: user.getDisplayName().toString(),
          registerDate: userExtra.getCreateTime(),
          lastLogin: userExtra.getLastSignInTime()
        }
        resolve(loginRes);
      }).catch((err) => {
        LogUtil.error(`Email login failed. Cause: ${JSON.stringify(err)}`);
        reject(err);
      });
    });
  }
}